<?php


namespace app\home\controller;


use app\admin\model\CheckInModel;
use app\admin\model\QuanGuanMemberModel;
use app\enums\enum\GenderEnum;
use app\home\services\CityService;
use app\home\services\StoreService;
use app\home\services\MemberService;
use app\utils\Response;
use think\Db;
use think\Exception;

class MemberController extends ApiBase
{
    /**
     * 注册
     */
    public function register()
    {
        $memberModel = new QuanGuanMemberModel();
        $memberService = new MemberService();
        if (!checkMobile($this->requestData['mobile'])) {
            Response::fail("手机号格式不正确");
        }
        $memberInfo = $memberService->getMemberInfoByMobile($this->requestData['mobile']);
        if (!empty($memberInfo)) {
            Response::fail("当前手机号已经被注册");
        }
        if ($this->requestData["password"] !== $this->requestData["qr_password"]) {
            Response::fail("两次密码不一致");
        }
        $hash = password_hash($this->requestData["password"], PASSWORD_DEFAULT);
        $this->requestData['password'] = $hash;
        unset($this->requestData['qr_password']);
        unset($this->requestData['image']);
        $this->requestData['create_time'] = time();
        $this->requestData['last_login_time'] = time();

        Db::startTrans();
        try {
            $res = $memberModel->save($this->requestData);
            $token = resectToken($memberModel->id);
            $tokenExpirceTime = time() + 3600 * config('quanguan.TOKEN_EXPIRE_HOUR');
            $memberInfo = $memberModel->find($memberModel->id);
            $memberInfo->token = $token;
            $memberInfo->token_expire_time = $tokenExpirceTime;
            $memberInfo->save();

            // 新用户，生成签到数据
            if( $this->requestData['identity'] == 1 ){
                $checkInModel = new CheckInModel();
                $checkInModel->create_id = $memberInfo['id'];
                $checkInModel->check_date = date("Y-m-d",time());
                $checkInModel->save();
            }

            // 拳馆信息
            $storeService = new StoreService();
            if ($this->requestData['identity'] == 4) {
                $storeInfo = [
                    'link_mobile' => $this->requestData['store_mobile'],
                    'title' => $this->requestData['store_title'],
                    'member_id' => $memberModel->id,
                    'address' => $this->requestData['store_address'],
                    'link_name' => $this->requestData['store_name'],
                    'province_id' => (int)$this->requestData['province_id'],
                    'city_id' => (int)$this->requestData['city_id'],
                    'area_id' => (int)$this->requestData['area_id'],
                    'add_time' => time()
                ];
                [$storeRes, $msg, $storeId] = $storeService->save(0, $storeInfo);
                if ($storeRes == 0) {
                    $memberInfo->store_id = $storeId;
                    $memberInfo->save();
                    Db::commit();
                } else {
                    throw new Exception("拳馆添加失败");
                }
            } else {
                Db::commit();
            }
        } catch (\Exception $e) {
            Db::rollback();
            Response::fail(var_export($e->getMessage()));
        }

        Response::success([
            'token' => $token,
            'identity' => $this->requestData['identity'],
            'store_id' => $memberInfo->store_id
        ]);
    }

    /**
     * 登录
     */
    public function login()
    {
        $checkMobile = checkMobile($this->requestData['mobile']);
        if (!$checkMobile) {
            Response::fail("手机号格式不正确");
        }
        $memberService = new MemberService();
        $memberInfo = $memberService->getMemberInfoByMobile($this->requestData['mobile']);
        if (empty($memberInfo)) {
            Response::fail("用户信息不存在");
        }
        if (!checkPwdHash($this->requestData['password'], $memberInfo['password'])) {
            Response::fail("密码不正确");
        }
        if ($memberInfo->status == 2) {
            Response::fail("账号已经被禁用");
        }
        $token = resectToken($memberInfo['id']);
        $memberInfo->last_login_time = time();
        $memberInfo->token_expire_time = time() + 3600 * config('quanguan.TOKEN_EXPIRE_HOUR');
        $memberInfo->token = $token;
        $memberInfo->save();
        Response::success([
            'token' => $token,
            'identity' => $memberInfo->identity,
            'store_id' => $memberInfo->store_id,
            'coach_id' => $memberInfo->coach_id,
        ]);
    }

    /**
     * 获取用户基本信息
     */
    public function getMemberInfo()
    {
        $token = trim($this->memberInfo['token']);
        $memberService = new MemberService();
        $storeService = new StoreService();
        $cityService = new CityService();
        $checkInModel = new CheckInModel();
        // 基本信息
        $memberInfo = $memberService->getMemberInfoByToken($token, ['id', 'name', 'age', 'gender', 'weight', 'identity', 'store_id', 'image', 'coach_id', 'mobile']);
        $memberInfo['image'] = env('DOMAIN_PATH') . $memberInfo['image'];
        // 店铺信息
        $storeInfo = $storeService->getInfoById($memberInfo['store_id'], ['id', 'title', 'link_mobile', 'province_id', 'city_id', 'area_id', 'address']);
        $areaList = $cityService->getDataByIds([$storeInfo['province_id'], $storeInfo['city_id'], $storeInfo['area_id']], ['cid', 'title', 'level']);
        $areaTitleList = CityController::getAllName($areaList);
        if ($storeInfo) {
            $storeInfo = $storeInfo->toArray();
        }
        $storeInfo = array_merge($storeInfo, $areaTitleList);
        // 教练信息
        $coachInfo = $memberService->getMemberInfoById($memberInfo['coach_id'], ['id', 'name', 'mobile', 'image']);
        $coachInfo['image'] = env('DOMAIN_PATH') . $coachInfo['image'];
        // 最大训练次数
        $maxCheckNum = 0;
        $maxCheckInfo = $checkInModel->where([
            'create_id' => $this->memberInfo['id'],
            'status' => 1,
            'is_delete' => 1,
            'is_check' => 1
        ])->order('num', 'desc')->limit(1)->find();
        if (!empty($maxCheckInfo)) {
            $maxCheckNum = $maxCheckInfo['num'];
        }
        Response::success([
            'member_info' => $memberInfo,
            'store_info' => $storeInfo,
            'coach_info' => $coachInfo,
            'check_info' => [
                'max_check_num' => $maxCheckNum
            ],
        ]);
    }

    /**
     * 设置用户信息
     */
    public function save()
    {
        $memberService = new MemberService();
        if (!isset($this->requestData['id'])) {
            Response::fail("id必传");
        }
        $id = (int)$this->requestData['id'];

        $checkMobile = false;
        if (isset($this->requestData['mobile']) && !empty($this->requestData['mobile'])) {
            $checkMobile = checkMobile($this->requestData['mobile']);
            if (!$checkMobile) {
                Response::fail("手机号格式不正确");
            }
        }
        if (!isset($this->requestData['store_id'])) {
            Response::fail("store_id为必填");
        }
        if (!isset($this->requestData['coach_id'])) {
            Response::fail("coach_id为必填");
        }

        $this->requestData['image'] = str_replace(env('DOMAIN_PATH'), '', $this->requestData['image']);

        $memberName = trim($this->requestData['name']);
        $gender = (int)$this->requestData['gender'];
        $image = trim($this->requestData['image']);
        $storeId = (int)$this->requestData['store_id'];
        $coachId = (int)$this->requestData['coach_id'];
        $identity = (int)$this->requestData['identity'];

        $memberData = [];
        if ($memberName != "") {
            $memberData['name'] = $memberName;
        }
        if ($gender != 0) {
            $memberData['gender'] = $gender;
        }
        if ($image != "") {
            $memberData['image'] = $image;
        }
        if ($identity != 0) {
            $memberData['identity'] = $identity;
        }
        if ($storeId != 0 && $coachId != 0) {
            $memberData['identity'] = 2;
        }
        if ($checkMobile) {
            $memberData['mobile'] = $this->requestData['mobile'];
        }
        $memberData['store_id'] = $storeId;
        $memberData['coach_id'] = $coachId;
        if( isset($this->requestData['password']) ){
            if( empty(trim($this->requestData['password'])) ){
                Response::fail("密码不能为空");
            }
            $memberData['password'] = password_hash($this->requestData["password"], PASSWORD_DEFAULT);
        }

        [$code, $msg, $id] = $memberService->save($id, $memberData);
        if ($code == 0) {
            Response::success([], $msg);
        } else {
            Response::fail($msg);

        }
    }

    /**
     * 获取当前拳馆下面所有的教练
     */
    public function getCoachListByStoreId()
    {
        $memberService = new MemberService();
        if (!isset($this->requestData['store_id']) || (int)$this->requestData['store_id'] <= 0) {
            Response::fail("store_id必传");
        }
        $storeId = (int)$this->requestData['store_id'];
        $list = $memberService->getCoachListByStoreId($storeId, ['id', 'name', 'image', 'gender', 'mobile']);
        foreach ($list as &$item) {
            $item['image'] = env('DOMAIN_PATH') . $item['image'];
            $item['gender_zh'] = GenderEnum::getEnumInfo($item['gender']);
        }
        Response::success([
            'coach_list' => $list
        ]);
    }

    /**
     * 学员绑定教练
     */
    public function studentBindCoach()
    {
        $memberService = new MemberService();
        if (!isset($this->requestData['coach_id']) || (int)$this->requestData['coach_id'] <= 0) {
            Response::fail("coach_id必传");
        }
        // 教练id
        $coachId = (int)$this->requestData['coach_id'];
        $coachInfo = $memberService->getMemberInfoById($coachId, ['id', 'store_id']);
        // 当前用户
        $memberInfo = $memberService->getMemberInfoByToken($this->memberInfo['token'], ['id', 'store_id', 'coach_id']);
        if ((int)$coachInfo['store_id'] <= 0) {
            Response::fail("教练所属道馆信息异常");
        }
        if ($coachId == $memberInfo['coach_id']) {
            Response::fail("教练信息一样，无需换绑");
        }
        $memberInfo->store_id = $coachInfo['store_id'];
        $memberInfo->coach_id = $coachInfo['id'];
        $memberInfo->identity = 2;
        $res = $memberInfo->save();
        Response::success();
    }

    /**
     * 馆长和教练获取自己的学员列表
     */
    public function getStudentList()
    {
        $memberModel = new QuanGuanMemberModel();
        if (!in_array($this->memberInfo['identity'], [3, 4])) {
            Response::fail("权限不足，无法查看");
        }
        if ($this->memberInfo['identity'] == 4) {
            if (!isset($this->requestData['store_id']) || (int)$this->requestData['store_id'] <= 0) {
                Response::fail("道馆id异常");
            }
        }
        $where = [];
        $where[] = ['status', 'eq', 1];
        $where[] = ['is_delete', 'eq', 1];
        $where[] = ['identity', 'eq', 2];
        $field = ['id', 'name', 'gender', 'image', 'weight', 'age'];
        if ($this->memberInfo['identity'] == 4) {
            $where[] = ['store_id', '=', $this->requestData['store_id']];
        }
        if ($this->memberInfo['identity'] == 3) {
            $where[] = ['coach_id', '=', $this->memberInfo['id']];
        }
        $studentList = $memberModel->where($where)->field($field)->select();
        $nan = 0;
        $nv = 0;
        foreach ($studentList as &$student) {
            $student['image'] = env('DOMAIN_PATH') . $student['image'];
            if ($student['gender'] == 1) {
                $nan += 1;
            }
            if ($student['gender'] == 2) {
                $nv += 1;
            }
            $student['gender_zh'] = GenderEnum::getEnumInfo($student['gender']);
        }
        Response::success([
            'student_list' => $studentList,
            'boy_num' => $nan,
            'girl_num' => $nv,
            'total' => (int)$nan + (int)$nv
        ]);
    }

    public function team()
    {
        var_dump(111);
        die;
    }
}